package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

// 分布式锁的内容
public class SimpleRedisLock implements ILock {
    private StringRedisTemplate stringRedisTemplate;
    private String name;
    public SimpleRedisLock(StringRedisTemplate stringRedisTemplate, String name) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.name = name;
    }
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;

    static{
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
    }
    private static final String KEY_PREFIX = "lock:";
    // 这个是解决 不同线程 抢占释放锁的内容
    private static final String ID_PREFIX = UUID.randomUUID().toString();
    @Override
    public boolean tryLock(Long timeoutSec) {
        String id = ID_PREFIX + "-" + Thread.currentThread().getId();
        Boolean b = stringRedisTemplate.opsForValue()
                .setIfAbsent(KEY_PREFIX + name, id, timeoutSec, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(b);
    }
    @Override
    public void unlock() {
        String key = ID_PREFIX + "-" + Thread.currentThread().getId();
        String lockKey = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
        if (key.equals(lockKey)) {
            stringRedisTemplate.delete(KEY_PREFIX + name);
        }
//        stringRedisTemplate.execute(UNLOCK_SCRIPT, Collections.singletonList( ID_PREFIX + "-" + Thread.currentThread().getId()))
    }
}
